import React, { useState, useRef, useEffect } from 'react';
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Radio,
  Space,
  Button,
  Upload,
  message,
  Modal,
} from 'antd';
import { Link } from 'react-router-dom';
import { UploadOutlined } from '@ant-design/icons';
import ChannelSelect from 'components/ChannelSelect';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import styles from './index.module.scss';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';
import { editArticle, getArticleDetail, publicArticle } from 'api/article';
export default function ArticlePublish(_props) {
  // console.log(_props);
  const articleId = _props.match.params.id;
  const [imgSrc, setImgSrc] = useState('');
  const [fileList, setFileList] = useState([]);
  const [coverType, setCoverType] = useState(1);
  const draftRef = useRef(false);
  const formRef = useRef();
  const props = {
    name: 'image',
    accept: '.jpg,.jpeg,.png', //用于设定筛选用户上传时的文件格式
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    // 数据发生变化时的回调
    onChange(info) {
      // console.log(info);
      setFileList(info.fileList);
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
    // 预览
    onPreview(file) {
      setImgSrc(file.thumbUrl ? file.thumbUrl : file.url);
    },
    // 图片上传前的回调
    beforeUpload(file, fileList) {
      // console.log(file);
      const imgs = ['image/png', 'image/jpg', 'image/jpeg'];
      if (!imgs.includes(file.type)) {
        message.warning('不支持的图片格式', 1);
        return Upload.LIST_IGNORE; //阻止发请求。也不显示在前端界面上
      }
      if (file.size > 1024 * 1024) {
        message.warning('图片不能大于1mb', 1);
        return Upload.LIST_IGNORE;
      }
    },
  };
  // 获取文章详情并回显
  const getArtDetail = async () => {
    formRef.current.setFieldsValue({});
    const res = await getArticleDetail(articleId);
    formRef.current.setFieldsValue({
      ...res.data,
      type: res.data.cover.type,
    });
    setFileList(
      res.data.cover.images.map((item) => {
        return { url: item };
      })
    );
    setCoverType(res.data.cover.type);
  };
  useEffect(() => {
    if (articleId) {
      getArtDetail();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  // 表单里的值改变时的触发的函数
  function handleValuesChange(changeValue, allValue) {
    // console.log(changeValue, allValue);
    if (changeValue.type !== undefined) {
      setCoverType(changeValue.type);
    }
  }
  // 图片数量控制
  const coverList = fileList.filter((item, index) => {
    if (coverType === 1) return index === 0;
    if (coverType === 0) return false;
    return true;
  });
  // 发表文章
  const onFinish = async (val) => {
    // console.log(val);
    // 1. 加判断条件 -数量不对,提示用户阻止执行
    if (coverList.length !== coverType) {
      return message.warning('图片数量不正确', 1);
    }
    let formDate = {
      ...val,
    };
    formDate.cover = {
      type: val.type,
      // 2. 以用户界面上看到的为准，发给后台
      images: coverList.map((item) => {
        return item.response ? item.response.data.url : item.url;
      }),
    };
    delete formDate.type;
    // console.log(formDate);
    if (articleId) {
      await editArticle(formDate, articleId, draftRef.current);
    } else {
      await publicArticle(formDate, draftRef.current);
    }
    message.success(
      draftRef.current ? '存入草稿成功' : articleId ? '编辑成功' : '发表成功',
      1
    );
    draftRef.current = false;
    _props.history.push('/list');
  };
  return (
    <div
      className={styles.root}
      style={{ height: 'calc (100vh - 64px)', overflow: 'auto', padding: 24 }}
    >
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{articleId ? '编辑' : '发布'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          ref={formRef}
          labelCol={{ span: 4 }}
          initialValues={{ type: 1, content: '' }}
          onFinish={onFinish}
          onValuesChange={handleValuesChange}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ warticleIdth: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择频道' }]}
          >
            <ChannelSelect></ChannelSelect>
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[
              { required: true },
              {
                message: '请输入文本内容',
                validator: (_, value) => {
                  // 判断value的值为   返回失败的信息
                  // 1. 判断是否为空标签
                  // 2.使用自定义校验，返回  Promise.resolve() 代表通过。 Promise.reject()代表失败
                  if (value === '<p><br></p>' || !value) {
                    return Promise.reject(new Error('内容不能为空'));
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <ReactQuill theme="snow" placeholder="请输入文章内容..." />
          </Form.Item>
          <Form.Item label="封面" name="type">
            <Radio.Group>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
              {/* <Radio value={-1}>自动</Radio> */}
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Upload {...props} listType="picture-card" fileList={coverList}>
              {/* {fileList.length === coverType ? null : <UploadOutlined />} */}
              {fileList.length < coverType && <UploadOutlined />}
            </Upload>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {articleId ? '编辑文章' : '发布文章'}
              </Button>
              {/* 让存入草稿也冒泡触发onFinish表单事件 */}
              <Button
                size="large"
                htmlType="submit"
                onClick={() => {
                  draftRef.current = true;
                }}
              >
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Modal
        title="预览"
        visible={!!imgSrc}
        footer={null}
        onCancel={() => setImgSrc('')}
      >
        <img
          src={imgSrc}
          alt=""
          style={{
            width: '100%',
          }}
        />
      </Modal>
    </div>
  );
}
